package com.example.service;

import com.example.entity.ChargingPile;
import com.example.entity.message.Message;
import com.example.entity.message.impl.CallMessage;
import com.example.entity.message.impl.UMessage4;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;

public class UHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// TODO Auto-generated method stub
		Message message = (Message) msg;

		if (message.getBody() == null) {
			UMessage4 uMessage4 = new UMessage4();
			ChargingPile state = (ChargingPile) ctx.channel().attr(AttributeKey.valueOf("state")).get();
			if (uMessage4.equals(message)) {
				if (state.isInit()) {
					state.hasU();
					ctx.writeAndFlush(new CallMessage());
				} else {
					throw new Exception("出现非法报文");
				}
			} else {
				throw new Exception("接收到的U帧不合法");
			}
		} else {
			ctx.fireChannelRead(msg);
		}
	}
}
